#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
"""
@File    :   tar.py.py
@Time    :   2025-01-08 12:03
@Author  :   坐公交也用券
@Version :   1.0
@Contact :   faith01238@hotmail.com
@Homepage : https://liumou.site
@Desc    :   将编译好的SSH程序打包用于分发二进制安装
"""
import logging
import os
import shutil
import sys
import zipfile
from argparse import ArgumentParser
from datetime import datetime
from pathlib import Path

# 创建一个自定义的日志记录器
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

# 创建一个自定义的日志处理器，设置其输出格式
formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(filename)s:%(lineno)d | %(funcName)s | %(message)s')
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(formatter)
logger.addHandler(handler)


class Tar:
	def __init__(self, p, format="gztar"):
		self.p = p
		self.format = format
		self.now = datetime.now()
		self.now_time = self.now.strftime("%Y%m%d%H%M%S")
		self.pwd = os.getcwd()

	def tar(self):
		"""使用shutil打包tar.gz格式"""
		if os.path.exists(self.p):
			dir_name = os.path.basename(self.p)
			# 创建临时目录结构
			temp_dir = os.path.join(self.pwd, "temp_package")
			os.makedirs(temp_dir, exist_ok=True)
			# 创建openssh目录并复制内容
			target_dir = os.path.join(temp_dir, dir_name)
			shutil.copytree(self.p, target_dir)
			# 打包临时目录
			shutil.make_archive(dir_name, self.format, temp_dir)
			ext = ".tar.gz" if self.format == "gztar" else ".zip"
			logger.info(f"打包成功: {os.path.join(self.pwd, f'{dir_name}{ext}')}")
			# 清理临时目录
			shutil.rmtree(temp_dir)
		else:
			logger.error(f"打包失败: {self.p} 不存在")
			exit(1)

	def zip(self):
		"""使用zipfile打包zip格式"""
		if os.path.exists(self.p):
			dir_name = os.path.basename(self.p)
			zip_path = os.path.join(self.pwd, f"{dir_name}.zip")
			
			with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
				for root, dirs, files in os.walk(self.p):
					for file in files:
						file_path = os.path.join(root, file)
						# 在路径前添加openssh目录
						arcname = os.path.join(dir_name, os.path.relpath(file_path, self.p))
						# 获取原始文件权限
						st = os.stat(file_path)
						# 创建ZipInfo对象并设置权限
						zip_info = zipfile.ZipInfo.from_file(file_path, arcname)
						zip_info.external_attr = (st.st_mode & 0xFFFF) << 16  # 保留权限位
						with open(file_path, 'rb') as f:
							zf.writestr(zip_info, f.read())
			logger.info(f"打包成功: {zip_path}")
		else:
			logger.error(f"打包失败: {self.p} 不存在")
			exit(1)

	def start(self):
		if self.format == "zip":
			self.zip()
		else:
			self.tar()


if __name__ == '__main__':
	arg = ArgumentParser(description='当前脚本版本: 2025-5-28 11:35:58', prog="OpenSshTar")
	arg.add_argument('-p', '--path', help='编译好的SSH程序路径(默认:/usr/local/openssh/)', 
					type=str, default='/usr/local/openssh/')
	arg.add_argument('-f', '--format', help='压缩格式(gztar/zip)', type=str, 
					choices=['gztar', 'zip'], default='gztar')
	args = arg.parse_args()
	p = Path(args.path)
	if not p.exists():
		logger.error(f"{p} 不存在")
		exit(1)
	tar = Tar(p, args.format)
	tar.start()